#define _CRT_SECURE_NO_WARNINGS

class Solution {
public:
    bool isIPnum(string& s, int begin, int end)
    {
        if (begin > end)
            return false;
        if (begin != end && s[begin] == '0')
            return false;
        int num = 0;
        for (int i = begin; i <= end; i++)
        {
            if (s[i] > '9' || s[i] < '0')
                return false;
            num = num * 10 + (s[i] - '0');
            if (num > 255)
                return false;
        }
        return true;
    }

    void _restoreIpAddressesR(vector<string>& ret, string& s, int start, int& num)
    {
        if (num == 3)
        {
            if (isIPnum(s, start, s.size() - 1))
                ret.push_back(s);
            return;
        }
        for (int i = start; i < s.size(); i++)
        {
            if (isIPnum(s, start, i))
            {
                s.insert(s.begin() + i + 1, '.');
                _restoreIpAddressesR(ret, s, i + 2, ++num);
                --num;
                s.erase(s.begin() + i + 1);
            }
            else
                break;
        }
    }

    vector<string> restoreIpAddresses(string s) {
        vector<string> ret;
        int num = 0;
        string buffer;
        _restoreIpAddressesR(ret, s, 0, num);
        return ret;
    }
};

class Solution {
public:
    void _subsetsR(vector<vector<int>>& ret, vector<int>& tmp, vector<int>& nums, int start)
    {
        if (start == nums.size())
            return;
        for (int i = start; i < nums.size(); i++)
        {
            tmp.push_back(nums[i]);
            ret.push_back(tmp);
            _subsetsR(ret, tmp, nums, i + 1);
            tmp.pop_back();
        }
    }

    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ret;
        vector<int> tmp;
        ret.push_back(tmp);
        _subsetsR(ret, tmp, nums, 0);
        return ret;
    }
};

class Solution {
public:
    void _subsetsR(vector<vector<int>>& ret, vector<int>& tmp, vector<int>& nums, int start)
    {
        if (start == nums.size())
            return;
        for (int i = start; i < nums.size(); i++)
        {
            if (i != start && nums[i] == nums[i - 1])
                continue;
            tmp.push_back(nums[i]);
            ret.push_back(tmp);
            _subsetsR(ret, tmp, nums, i + 1);
            tmp.pop_back();
        }
    }

    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        vector<int> tmp;
        ret.push_back(tmp);
        _subsetsR(ret, tmp, nums, 0);
        return ret;
    }
};